package cn.usbtg.session.impl;

import cn.usbtg.core.exception.BTGRuntimeException;
import cn.usbtg.session.BTGSession;
import cn.usbtg.session.BTGSessionDao;
import cn.usbtg.sutil.EmptyUtil;

import java.util.Hashtable;
import java.util.Iterator;

/**
 * 基于本地容器的session存储实现
 */
public class BTGLocalSessionDao implements BTGSessionDao {
    private static Hashtable<String, BTGSession> sessionContext = new Hashtable<>();//session容器

    @Override
    public void saveSession(BTGSession session) {
        if (EmptyUtil.isEmpty(session)) {
            throw new BTGRuntimeException("session is null");
        }
        sessionContext.put(session.getId(), session);
    }

    @Override
    public void deleteSession(String sessionId) {
        if (EmptyUtil.isEmpty(sessionId)) {
            throw new BTGRuntimeException("session id is null");
        }
        sessionContext.remove(sessionId);
    }

    @Override
    public BTGSession getSession(String sessionId) {
        return sessionContext.get(sessionId);
    }

    @Override
    public void refreshSession(BTGSession session) {
        if (EmptyUtil.isEmpty(session)) {
            throw new BTGRuntimeException("session is null");
        }
        sessionContext.put(session.getId(), session);
    }

    @Override
    public void active(BTGSession session) {
        if (EmptyUtil.isEmpty(session)) {
            throw new BTGRuntimeException("session is null");
        }
        sessionContext.get(session.getId()).active();
    }

    @Override
    public Hashtable<String, BTGSession> getSessions() {
        return sessionContext;
    }

    @Override
    public void clearTimeout() {
        Iterator<BTGSession> iterator = sessionContext.values().iterator();
        while (iterator.hasNext()) {
            BTGSession session = iterator.next();
            if (session.isInvalidate()) {
                iterator.remove();
            }
        }
    }

    @Override
    public void clear() {
        sessionContext.clear();
    }
}